package org.eiahe.hr.salary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import org.eiahe.hr.salary.domain.EmployeePhoneAssociation;
import org.eiahe.hr.salary.domain.bo.EmployeePhoneAssociationBo;
import org.eiahe.hr.salary.domain.vo.EmployeePhoneAssociationVo;
import org.eiahe.hr.salary.mapper.EmployeePhoneAssociationMapper;
import org.eiahe.hr.salary.service.IEmployeePhoneAssociationService;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 员工手机关联Service业务层处理
 *
 * @author zhangnn
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EmployeePhoneAssociationServiceImpl implements IEmployeePhoneAssociationService {

    private final EmployeePhoneAssociationMapper baseMapper;
    private final ISysDeptService deptService;

    /**
     * 查询员工手机关联
     *
     * @param associationId 员工手机关联ID
     * @return 员工手机关联
     */
    @Override
    public EmployeePhoneAssociationVo queryById(Long associationId) {
        return baseMapper.selectVoById(associationId);
    }

    /**
     * 查询员工手机关联列表
     *
     * @param bo 员工手机关联业务对象
     * @return 员工手机关联集合
     */
    @Override
    public List<EmployeePhoneAssociationVo> queryList(EmployeePhoneAssociationBo bo) {
        LambdaQueryWrapper<EmployeePhoneAssociation> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 分页查询员工手机关联列表
     *
     * @param bo        员工手机关联业务对象
     * @param pageQuery 分页参数
     * @return 员工手机关联分页数据
     */
    @Override
    public TableDataInfo<EmployeePhoneAssociationVo> queryPageList(EmployeePhoneAssociationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EmployeePhoneAssociation> lqw = buildQueryWrapper(bo);
        Page<EmployeePhoneAssociationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 新增员工手机关联
     *
     * @param bo 员工手机关联业务对象
     * @return 是否成功
     */
    @Override
    public Boolean insertByBo(EmployeePhoneAssociationBo bo) {
        // 检查是否已存在该员工的关联记录
        LambdaQueryWrapper<EmployeePhoneAssociation> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(EmployeePhoneAssociation::getEmployeeNo, bo.getEmployeeNo());
        queryWrapper.eq(EmployeePhoneAssociation::getDelFlag, "0");
        EmployeePhoneAssociation existing = baseMapper.selectOne(queryWrapper);

        if (existing != null) {
            // 如果已存在，则更新现有记录而不是新增
            EmployeePhoneAssociation update = MapstructUtils.convert(bo, EmployeePhoneAssociation.class);
            update.setAssociationId(existing.getAssociationId()); // 保留原有ID
            validEntityBeforeSave(update);
            return baseMapper.updateById(update) > 0;
        } else {
            // 如果不存在，则新增记录
            EmployeePhoneAssociation add = MapstructUtils.convert(bo, EmployeePhoneAssociation.class);
            validEntityBeforeSave(add);
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setAssociationId(add.getAssociationId());
            }
            return flag;
        }
    }

    /**
     * 修改员工手机关联
     *
     * @param bo 员工手机关联业务对象
     * @return 是否成功
     */
    @Override
    public Boolean updateByBo(EmployeePhoneAssociationBo bo) {
        // 检查是否存在该记录
        if (bo.getAssociationId() == null) {
            throw new RuntimeException("关联ID不能为空");
        }

        EmployeePhoneAssociation existing = baseMapper.selectById(bo.getAssociationId());
        if (existing == null) {
            throw new RuntimeException("员工手机关联记录不存在");
        }

        EmployeePhoneAssociation update = MapstructUtils.convert(bo, EmployeePhoneAssociation.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除员工手机关联
     *
     * @param ids 员工手机关联ID数组
     * @return 是否成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 验证员工手机号 - 短信验证码方式
     *
     * @param associationId 员工手机关联ID
     * @param captcha       短信验证码
     * @return 是否成功
     */
    @Override
    public Boolean verifyPhoneNumberByCaptcha(Long associationId, String captcha) {
        EmployeePhoneAssociation association = baseMapper.selectById(associationId);
        if (association == null) {
            log.warn("员工手机关联记录不存在，associationId: {}", associationId);
            return false;
        }

        // TODO: 实际项目中应该调用短信服务验证验证码
        // 这里简化处理，假设验证码为"123456"
        if (!"123456".equals(captcha)) {
            log.warn("短信验证码错误，associationId: {}", associationId);
            throw new RuntimeException("短信验证码错误");
        }

        // 更新验证状态为已验证
        association.setVerificationStatus("1");
        association.setVerificationMethod("短信验证码");
        association.setAssociationTime(new Date()); // 更新关联时间为验证时间
        return baseMapper.updateById(association) > 0;
    }

    /**
     * 验证员工手机号 - 人脸识别方式
     *
     * @param associationId 员工手机关联ID
     * @param faceData      人脸数据
     * @return 是否成功
     */
    @Override
    public Boolean verifyPhoneNumberByFace(Long associationId, String faceData) {
        EmployeePhoneAssociation association = baseMapper.selectById(associationId);
        if (association == null) {
            log.warn("员工手机关联记录不存在，associationId: {}", associationId);
            return false;
        }

        // TODO: 实际项目中应该调用人脸识别服务验证
        // 这里简化处理，假设人脸识别总是成功
        if (StringUtils.isBlank(faceData)) {
            log.warn("人脸识别数据为空，associationId: {}", associationId);
            throw new RuntimeException("人脸识别数据不能为空");
        }

        // 更新验证状态为已验证
        association.setVerificationStatus("1");
        association.setVerificationMethod("人脸识别");
        association.setAssociationTime(new Date()); // 更新关联时间为验证时间
        return baseMapper.updateById(association) > 0;
    }

    /**
     * 检查员工手机号是否已验证
     *
     * @param employeeNo 工号
     * @return 是否已验证
     */
    @Override
    public Boolean isPhoneNumberVerified(String employeeNo) {
        LambdaQueryWrapper<EmployeePhoneAssociation> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(EmployeePhoneAssociation::getEmployeeNo, employeeNo);
        queryWrapper.eq(EmployeePhoneAssociation::getVerificationStatus, "1");
        queryWrapper.eq(EmployeePhoneAssociation::getDelFlag, "0");
        // 查询是否存在已验证的记录
        EmployeePhoneAssociation association = baseMapper.selectOne(queryWrapper);
        return association != null;
    }

    /**
     * 构建查询条件
     *
     * @param bo 员工手机关联业务对象
     * @return 查询条件
     */
    private LambdaQueryWrapper<EmployeePhoneAssociation> buildQueryWrapper(EmployeePhoneAssociationBo bo) {
        LambdaQueryWrapper<EmployeePhoneAssociation> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTenantId()), EmployeePhoneAssociation::getTenantId, bo.getTenantId());
        lqw.eq(StringUtils.isNotBlank(bo.getEmployeeNo()), EmployeePhoneAssociation::getEmployeeNo, bo.getEmployeeNo());
        lqw.eq(StringUtils.isNotBlank(bo.getPhoneNumber()), EmployeePhoneAssociation::getPhoneNumber,
                bo.getPhoneNumber());
        lqw.eq(bo.getAssociationTime() != null, EmployeePhoneAssociation::getAssociationTime, bo.getAssociationTime());
        lqw.eq(StringUtils.isNotBlank(bo.getVerificationStatus()), EmployeePhoneAssociation::getVerificationStatus,
                bo.getVerificationStatus());
        return lqw;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(EmployeePhoneAssociation entity) {
        // 校验员工工号是否存在
        if (StringUtils.isBlank(entity.getEmployeeNo())) {
            throw new RuntimeException("员工工号不能为空");
        }

        // 校验手机号不能为空
        if (StringUtils.isBlank(entity.getPhoneNumber())) {
            throw new RuntimeException("手机号不能为空");
        }

        // 校验手机号格式
        if (!entity.getPhoneNumber().matches("^1[3-9]\\d{9}$")) {
            throw new RuntimeException("手机号格式不正确");
        }

        // 校验关联时间不能为空
        if (entity.getAssociationTime() == null) {
            throw new RuntimeException("关联时间不能为空");
        }

        // 校验状态合法性
        if (StringUtils.isNotBlank(entity.getVerificationStatus()) &&
                !"0".equals(entity.getVerificationStatus()) && !"1".equals(entity.getVerificationStatus())) {
            throw new RuntimeException("验证状态只能是0(未验证)或1(已验证)");
        }
    }
}
